package com.hthy.futures.ui.activity;


import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hthy.futures.AppConfig;
import com.hthy.futures.AppContext;
import com.hthy.futures.R;
import com.hthy.futures.UIHelper;
import com.hthy.futures.api.ST_TradeApi;
import com.hthy.futures.base.BaseActivity;
import com.hthy.futures.base.CommonAdapter;
import com.hthy.futures.base.CommonViewHolder;
import com.hthy.futures.bean.AppConfigContext;
import com.hthy.futures.ui.ServiceDialog;
import com.hthy.futures.utils.DialogHelp;
import com.hthy.futures.utils.DialogUtil;
import com.hthy.futures.utils.ErrorUtils;
import com.hthy.futures.utils.GlideUtils;
import com.hthy.futures.utils.LogUtils;
import com.hthy.futures.utils.SPUtils;
import com.hthy.futures.utils.ShaUtils;
import com.hthy.futures.utils.SoftHideKeyBoardUtil;
import com.hthy.futures.utils.StringUtils;
import com.hthy.futures.utils.TDevice;
import com.hthy.futures.view.MyTextWatcher;
import com.hthy.futures.view.ToggleButton;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.vilyever.socketclient.SocketClient;
import com.vilyever.socketclient.helper.SocketClientDelegate;
import com.vilyever.socketclient.helper.SocketPacket;
import com.vilyever.socketclient.helper.SocketResponsePacket;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import net.hthy.bean.Trade;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;

public class LoginActivity extends BaseActivity implements SocketClientDelegate {
    @Bind(R.id.tv_tradename)
    TextView tvTradeName;
    @Bind(R.id.et_username)
    EditText mEtUsername;
    @Bind(R.id.iv_clear)
    ImageView ivClear;
    @Bind(R.id.iv_clear2)
    ImageView ivClear2;
    @Bind(R.id.et_pwd)
    EditText mEtPwd;
    @Bind(R.id.cb_rember_me)
    ToggleButton mCbRember;
    @Bind(R.id.ll_login_username)
    LinearLayout mLlLoginUsername;
    @Bind(R.id.ll_login_pwd)
    LinearLayout mLllogingPwd;
    @Bind(R.id.activity_login)
    RelativeLayout main;

    private SocketClient socketClient;
    private String username;
    private String pwd;
    private boolean mIsChecket;
    private boolean isFromLogin = false;
    private String mLogingStr;
    private ServiceDialog mServiceDialog;


    @Bind(R.id.bt_login)
    Button login_btn;
    private boolean mParseBoolean;

    @Bind(R.id.iv_seach)
    ImageView iLogo;
    private byte[] mLoginByte;
    private boolean isLoggin  = false;

    @Override
    protected int getContentView() {
        return R.layout.activity_login;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        checkNewVersion();
        String logo = SPUtils.getFromPrefs(this, AppConfig.logo, "");
        GlideUtils.setImageCenter(this, !StringUtils.isEmpty(logo) ? logo : null, iLogo);

        /*String saveServiceType = SPUtils.getFromPrefs(this, getResources().getString(R.string.serviceType), "");
        if (!StringUtils.isEmpty(saveServiceType)) {
            tvTradeName.setText(saveServiceType);
        } else {
            tvTradeName.setText(AppContext.defaultServiceName);
        }*/
        tvTradeName.setText(AppContext.defaultServiceName);

        // 初始化huangtai
        mEtUsername.setText(SPUtils.getFromPrefs(this, getResources().getString(R.string.account), ""));
        mEtPwd.setText(SPUtils.getFromPrefs(this, getResources().getString(R.string.pwd), ""));


        socketClient = ((AppContext) getApplication()).getSocketClient();

        if (socketClient != null) {
            socketClient.registerSocketClientDelegate(this);
        }

        mCbRember.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
            @Override
            public void onToggle(boolean isChecked) {
                mIsChecket = isChecked;
                if (isChecked) {
                    savaUserInfo();
                } else {
                    clearUserInfo();
                }
            }
        });
        String aFalse = SPUtils.getFromPrefs(this, getResources().getString(R.string.ischecket), "false");
        mParseBoolean = Boolean.parseBoolean(aFalse);
        if (mParseBoolean) {
            mCbRember.setToggleOn();
        } else {
            mCbRember.setToggleOff();
        }


        SoftHideKeyBoardUtil.addLayoutListener2(main, login_btn);

        // 后面如果跟上textwatcher的话有bug  (x图片得设置成View.INVISIBLE模式就没有bug了）
        //ivClear.setVisibility(View.INVISIBLE);
        ivClear2.setVisibility(View.INVISIBLE);
        mEtUsername.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                ivClear.setVisibility(StringUtils.isEmpty(s) ? View.INVISIBLE : View.VISIBLE);
            }
        });
        mEtPwd.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                ivClear2.setVisibility(StringUtils.isEmpty(s) ? View.INVISIBLE : View.VISIBLE);
            }
        });


        // 选中某个交易商回调
        SearchActivity.setOnServiceSelected(new SearchActivity.OnServiceItemSelectedListener() {
            @Override
            public void onselect(AppConfigContext appconfigContext) {
                initClearSocketClient();

                AppContext.setNewService(appconfigContext);

                socketClient = ((AppContext) getApplication()).getSocketClient();

                socketClient.registerSocketClientDelegate(LoginActivity.this);

                GlideUtils.setImageCenter(LoginActivity.this, appconfigContext.getLogo_uri(), iLogo);

               /* mEtUsername.setText("");
                mEtPwd.setText("");*/
            }
        });
    }

    /**
     * 检查最新的版本
     */
    private void checkNewVersion() {
        // 如果检查到有新版本的，就去弹出一个下载地址的APP弹出款，否则直接跳到登录页。
        int versionCode = TDevice.getVersionCode();
        // 版本号是整数的，版本名字倒是可以是任意的。
        if (AppContext.appCode > versionCode) {
            /*AlertDialog.Builder dialog = DialogHelp.getConfirmDialog(LoginActivity.this, "有新版本需要更新", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent itent = new Intent(Intent.ACTION_VIEW);
                    itent.setData(Uri.parse(AppContext.appDowloadUrl));
                    startActivity(itent);
                }
            });
            dialog.show();*/

            AlertDialog.Builder dialog = DialogHelp.getConfirmDialog(LoginActivity.this, "有新版本需要更新", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    UIHelper.openDownLoadService(LoginActivity.this, AppContext.appDowloadUrl, TDevice.getVersionName());
                }
            });
            dialog.setTitle("发现新版本");
            dialog.show();

            Acp.getInstance(this).request(new AcpOptions.Builder()
                            .setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            /*以下为自定义提示语、按钮文字
                            .setDeniedMessage()
                            .setDeniedCloseBtn()
                            .setDeniedSettingBtn()
                            .setRationalMessage()
                            .setRationalBtn()*/
                            .build(),
                    new AcpListener() {
                        @Override
                        public void onGranted() {
                        }

                        @Override
                        public void onDenied(List<String> permissions) {
                            //showToast(permissions.toString() + "权限拒绝");
                        }
                    });
        }
    }

    private void clearUserInfo() {
        SPUtils.saveToPrefs(LoginActivity.this, getResources().getString(R.string.account), "");
        SPUtils.saveToPrefs(LoginActivity.this, getResources().getString(R.string.pwd), "");
        SPUtils.saveToPrefs(LoginActivity.this, getResources().getString(R.string.ischecket), "false");
    }

    /**
     * 保存用户信息
     */
    private void savaUserInfo() {
        // 还要保存服务商类型
        SPUtils.saveToPrefs(LoginActivity.this, getString(R.string.serviceType), tvTradeName.getText().toString().trim());
        SPUtils.saveToPrefs(LoginActivity.this, getResources().getString(R.string.account), mEtUsername.getText().toString().trim());
        SPUtils.saveToPrefs(LoginActivity.this, getResources().getString(R.string.pwd), mEtPwd.getText().toString().trim());
        SPUtils.saveToPrefs(this, getResources().getString(R.string.ischecket), "" + true);
    }


    @OnClick({R.id.iv_reflesh, R.id.trade_choose, R.id.iv_clear, R.id.iv_clear2, R.id.iv_seach, R.id.bt_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_reflesh:
                isLoggin = false;
                // 请求交易中心json数据
                LogUtils.e("config", AppContext.tongnanEnv + "------" + AppConfig.query_data);
                String queryData = SPUtils.getFromPrefs(this, AppConfig.query_data, "");
                OkHttpUtils
                        .get()//
                        .url(AppConfig.TEADE_CENTER)//
                        .addParams(getString(R.string.query_type), getString(R.string.config))
                        .addParams(getString(R.string.query_data), !StringUtils.isEmpty(queryData) ? queryData : AppConfig.query_data)
                        .build()//
                        .execute(new MyStringCallback());
                break;
            case R.id.trade_choose:
                CommonAdapter<AppConfigContext.ServerTypeBean> mServiceAdapter = new CommonAdapter<AppConfigContext.ServerTypeBean>(LoginActivity.this, R.layout.spin_view) {
                    @Override
                    public void convert(CommonViewHolder vh, AppConfigContext.ServerTypeBean item) {
                        vh.setText(R.id.spin_value, item.getName());
                    }
                };
                if (mServiceDialog == null) {
                    mServiceDialog = new ServiceDialog(this);
                }
                mServiceDialog.setServiceTypeItemSelectedListener(new ServiceDialog.OnServiceTypeItemSelectedListener() {
                    @Override
                    public void select(AppConfigContext.ServerTypeBean serverTypeBean) {
                        isLoggin = false;
                        LogUtils.e("test",serverTypeBean.getTrade_gate());
                        // 做一些
                        initClearSocketClient();

                        AppContext.setContextAddress(serverTypeBean);

                        socketClient = ((AppContext) getApplication()).getSocketClient();

                        socketClient.registerSocketClientDelegate(LoginActivity.this);

                        tvTradeName.setText(serverTypeBean.getName());

                        // 是否要保存信息
                        String aFalse = SPUtils.getFromPrefs(LoginActivity.this, getResources().getString(R.string.ischecket), "false");
                        mParseBoolean = Boolean.parseBoolean(aFalse);
                        if (mParseBoolean) {
                            SPUtils.saveToPrefs(LoginActivity.this, getString(R.string.serviceType), tvTradeName.getText().toString().trim());
                        }
                    }
                });
                if (mServiceAdapter != null) {
                    mServiceDialog.setServiceAdapter(mServiceAdapter);
                }
                mServiceDialog.setCancelable(false);
                mServiceDialog.setCanceledOnTouchOutside(true);
                mServiceDialog.show();
                break;
            case R.id.iv_seach:
                if (!AppContext.tongnanEnv) {
                    startActivity(new Intent(LoginActivity.this, SearchActivity.class));
                }
                break;

            case R.id.iv_clear:
                mEtUsername.setText("");
                break;

            case R.id.iv_clear2:
                mEtPwd.setText("");
                break;

            case R.id.bt_login:
                String aFalse = SPUtils.getFromPrefs(this, getResources().getString(R.string.ischecket), "false");
                mParseBoolean = Boolean.parseBoolean(aFalse);
                if (mParseBoolean) {
                    savaUserInfo();
                } else {
                    clearUserInfo();
                }
                if (!TDevice.hasInternet()) {
                    showToast(R.string.net_tip);
                    return;
                }
                username = mEtUsername.getText().toString().trim();
                pwd = mEtPwd.getText().toString().trim();

                AppContext.account = username;
                AppContext.accountPwd = pwd;
                if (StringUtils.isEmpty(username)) {
                    showToast(R.string.username_tip);
                    return;
                }
                if (StringUtils.isEmpty(pwd)) {
                    showToast(R.string.pwd_tip);
                    return;
                }
                //DialogUtil.showDialog(this);

                //  mLogingStr = ST_TradeApi.login(username, ShaUtils.getSha1(pwd));
                mLoginByte = ST_TradeApi.login(username, ShaUtils.getSha1(pwd));

                DialogUtil.showDialog(this);
                if (socketClient != null && !socketClient.isConnected()) {
                    socketClient.connect();
                    isFromLogin = true;
                }
                // socketClient.sendString(mLogingStr);
                isLoggin = true;
                socketClient.sendData(mLoginByte);
                break;
        }
    }

    /**
     * 消除socketClient操作
     */
    private void initClearSocketClient() {
        if (socketClient != null) {
            socketClient.disconnect();
            socketClient.removeSocketClientDelegate(LoginActivity.this);
            socketClient = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (socketClient != null) {
            socketClient.removeSocketClientDelegate(this);
        }
        // EventBus.getDefault().unregister(this);
    }

    @Override
    public void onConnected(SocketClient client) {
        LogUtils.e("connect");
        SocketPacket packet = socketClient.sendData(new byte[]{0x02}); // 发送消息
        //packet = socketClient.sendString("sy hi!"); // 发送消息
        // 必须得加这一句话，不然没效果
        socketClient.cancelSend(packet); // 取消发送，若在等待发送队列中则从队列中移除，若已发送完成则无法取消，若正在发送且分段发送则取消发送剩余数据（此时若没有设置包头用于远程端判断下一个信息包的开始可能出现粘包或数据不全问题）
        if (isFromLogin) {
            //socketClient.sendString(mLogingStr);
            socketClient.sendData(mLoginByte);
            isFromLogin = false;
        }
    }

    @Override
    public void onDisconnected(SocketClient client) {
        // 断开连接回调，可在此实现自动重连
        socketClient.connect();
        isFromLogin = true;
    }

    @Override
    public void onResponse(SocketClient client, @NonNull SocketResponsePacket responsePacket) {
        DialogUtil.dimissDialog();
        if (isLoggin) {
            String message = responsePacket.getMessage(); // 获取按默认设置的编码转化的String，可能为null
            LogUtils.e(message);

            // pb逻辑

            try {
                byte[] data = responsePacket.getData(); // 获取接收的byte数组，不为null
                byte[] bytes = StringUtils.subBytes(data, 37, data.length - 37);
                Trade.LoginResponseMsg loginResponseMsg = Trade.LoginResponseMsg.parseFrom(bytes);

                AppContext.accountId = loginResponseMsg.getUiUserUid();
                AppContext.sessionId = loginResponseMsg.getSsLoginSession();
                AppContext.accountName = loginResponseMsg.getUserInfo().getSsRealName();

                int iErrorCode = loginResponseMsg.getResponseMsg().getIErrorCode();
                if (0 == iErrorCode) {
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                } else {
                    ErrorUtils.sendErrorMes(this, iErrorCode + "");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 请求回调
     */
    public class MyStringCallback extends StringCallback {
        @Override
        public void onBefore(Request request, int id) {
            //DialogUtil.showDialog(LoginActivity.this);
        }


        @Override
        public void onError(Call call, Exception e, int id) {
            showToast(R.string.net_tip);
        }

        @Override
        public void onResponse(String response, int id) {
            LogUtils.e("config", response);
            initClearSocketClient();
            DialogUtil.dimissDialog();
            showToast(R.string.config_susscess);

            AppContext.parseJson(response);

            socketClient = ((AppContext) getApplication()).getSocketClient();

            socketClient.registerSocketClientDelegate(LoginActivity.this);

            tvTradeName.setText(AppContext.defaultServiceName);
        }
    }
}